import React, { createContext, useState, useContext, useEffect } from 'react';

// 创建主题上下文
const ThemeContext = createContext();

// 主题提供者组件
export const ThemeProvider = ({ children }) => {
  // 从本地存储加载主题设置，默认为'light'
  const [theme, setTheme] = useState(() => {
    const savedTheme = localStorage.getItem('theme');
    return savedTheme || 'light';
  });

  // 当主题变化时，保存到本地存储
  useEffect(() => {
    localStorage.setItem('theme', theme);
    // 更新文档根元素的类名，用于CSS样式切换
    document.documentElement.className = theme;
  }, [theme]);

  // 切换主题的函数
  const toggleTheme = () => {
    setTheme(prevTheme => prevTheme === 'light' ? 'dark' : 'light');
  };

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
};

// 自定义Hook，方便组件使用主题
export const useTheme = () => useContext(ThemeContext); 